<template>
  <div>
    <el-card :body-style="{ padding: 0 }" :bordered="false" class="ivu-mt" shadow="never">
      <div class="padding-add">
        <el-form
          ref="tableFrom"
          :label-position="labelPosition"
          :label-width="labelWidth"
          :model="tableFrom"
          inline
          @submit.native.prevent
        >
          <el-form-item label="搜索：" label-for="content">
            <el-input
              v-model="tableFrom.content"
              class="form_content_width"
              placeholder="请输入电话，姓名，编码，邮箱"
            />
          </el-form-item>

          <el-form-item label="金牌代理：" >
            <el-select v-model="tableFrom.is_gold" placeholder="请选择" f >
              <el-option label="全部" value=""></el-option>
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button v-db-click type="primary" @click="userSearchs">查询</el-button>
<!--            <el-button v-db-click type="success" @click="settlementAll">结算所有代理费用</el-button>-->
<!--            <el-button v-db-click type="warning" @click="exportSettlementData">导出代理结算数据</el-button>-->
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card :bordered="false" class="ivu-mt mt16" shadow="never">
      <!--      <el-button v-auth="['admin-agent_sy']" v-db-click icon="md-add" type="primary">导出代理收益</el-button>-->
      <div class="operation-buttons">
        <el-button v-db-click type="success" @click="handleBatchSettlement" :disabled="ids.length === 0">
          批量结算
        </el-button>
        <el-button v-db-click type="warning" @click="handleBatchExport" :disabled="ids.length === 0">
          批量导出
        </el-button>
        <el-button v-db-click type="primary" plain @click="handleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </el-button>
      </div>
      <div v-if="ids.length" class="selection-alert">
        <el-alert show-icon type="info" :closable="false">
          <template slot="title">
            已选择<i class="selection-count"> {{ ids.length }} </i>项
          </template>
        </el-alert>
      </div>
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableList"
        class="mt14"
        highlight-current-row
        no-filtered-userFrom-text="暂无筛选结果"
        no-userFrom-text="暂无数据"
      >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.isChecked"
              @change="(val) => handleCheckboxChange(val, scope.row)"
              :disabled="scope.row.status === 0"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="ID" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="被推荐的名称" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="被推荐的手机号" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>

        <el-table-column label="是否金牌代理" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.is_gold === 0"></span>
            <span v-else-if="scope.row.is_gold === 1">是</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="累计收益" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.brokerage }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上级代理名称" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.parent_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上级代理电话" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.parent_phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否已审核" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0">未审核</span>
            <span v-else-if="scope.row.status === 1">已审核</span>
            <span v-else>-</span>
            <!--            <span>{{ scope.row.status === 0 ?'未审核' :'已审核' }}</span>-->
          </template>
        </el-table-column>

        <el-table-column label="身份证号" min-width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.card_id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证正面照" min-width="90">
          <template slot-scope="scope">
            <div class="tabBox_img" v-viewer>
              <img v-lazy="scope.row.id_card_front" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="详细地址" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" min-width="100">
          <template slot-scope="scope">
            <span> {{ scope.row.mail }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="身份证正面照" min-width="120">-->
        <!--          <template slot-scope="scope">-->
        <!--            <div v-if="scope.row.id_card_front" class="tabBox_img" @click="openImg(scope.row.id_card_front)">-->
        <!--              <img :src="scope.row.id_card_front" alt="身份证正面照" />-->
        <!--            </div>-->
        <!--            <span v-else>-</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="性别" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.sex === 1">男</span>
            <span v-else-if="scope.row.sex === 0">女</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.age }}</span>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.add_time }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <a v-db-click @click="edit(scope.row.id)">编辑</a>
<!--            <el-divider direction="vertical"></el-divider>-->
<!--            <a v-db-click @click="editBrokerage(scope.row.id)">扣除佣金</a>-->
            <el-divider direction="vertical"></el-divider>
            <a v-db-click @click="selectChild(scope.row)">收益明细</a>
            <el-divider direction="vertical"></el-divider>
            <a v-db-click @click="exportMXList(scope.row)">导出收益明细</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :limit.sync="tableFrom.limit"
          :page.sync="tableFrom.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <childList ref="stock" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatDate } from '@/utils/validate';
import {
  editApi,
  editBrokerageApi,
  leaderBrokerageApi,
  leaderListApi,
  settlementAllApi,
  settlementLeaderBrokerageApi,
} from '@api/agent';
import childList from '../components/childList.vue';
import { exportUserList } from '@api/export';
import axios from 'axios';

export default {
  name: 'agent-list',
  components: {
    childList,
  },
  filters: {
    formatDate(time) {
      if (time !== 0) {
        let date = new Date(time * 1000);
        return formatDate(date, 'yyyy-MM-dd hh:mm');
      }
    },
  },
  data() {
    return {
      modals2: false,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,

      tableFrom: {
        content: '',
        page: 1,
        limit: 20,
        is_gold: '',
      },

      tableList: [],
      total: 0,
      ids: [], // 选中项的id数组
      isAllSelected: false, // 是否全选
    };
  },
  activated() {
    this.getList();
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapState('media', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : '90px';
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'right';
    },
    // 可选择的代理数量
    selectableAgents() {
      return this.tableList;
    },
  },
  methods: {
    // 全选/取消全选
    handleSelectAll() {
      if (this.isAllSelected) {
        // 如果当前是全选状态，则取消全选
        this.tableList.forEach((item) => {
          item.isChecked = false;
        });
        this.ids = [];
        this.isAllSelected = false;
      } else {
        // 如果当前不是全选状态，则全选（只选择已审核的代理）
        this.ids = [];
        this.tableList.forEach((item) => {
          if (item.status === 1) { // 只选择已审核的代理
            item.isChecked = true;
            if (!this.ids.includes(item.id)) {
              this.ids.push(item.id);
            }
          }
        });
        this.isAllSelected = this.ids.length > 0;
      }
    },

    // 处理复选框选择
    handleCheckboxChange(val, row) {
      if (row.status === 0) {
        return; // 未审核代理不允许选择
      }

      if (val) {
        // 如果选中，添加到ids数组
        if (!this.ids.includes(row.id)) {
          this.ids.push(row.id);
        }
      } else {
        // 如果取消选中，从ids数组中移除
        const index = this.ids.indexOf(row.id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
      }

      // 更新全选状态
      this.isAllSelected = this.selectableAgents.length > 0 && this.ids.length === this.selectableAgents.length;
    },

    // 批量结算
    handleBatchSettlement() {
      if (this.ids.length === 0) {
        this.$message.warning('请选择要结算的代理');
        return;
      }
      
      this.$msgbox({
        title: '批量结算',
        message: `确认对已选择的 ${this.ids.length} 个代理进行批量结算操作吗？`,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
      })
        .then(() => {
          this.loading = true;
          settlementAllApi({
            id: this.ids.join(',')
          })
            .then((res) => {
              this.$message.success(res.msg || '批量结算成功');
              this.ids = [];
              this.getList();
            })
            .catch((err) => {
              this.$message.error(err.msg || '批量结算失败');
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message.info('已取消结算');
        });
    },

    // 批量导出
    handleBatchExport() {
      if (this.ids.length === 0) {
        this.$message.warning('请选择要导出的代理');
        return;
      }
      
      this.$msgbox({
        title: '批量导出',
        message: `确认对已选择的 ${this.ids.length} 个代理进行批量导出操作吗？`,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
      })
        .then(() => {
          this.loading = true;
          settlementLeaderBrokerageApi({
            id: this.ids.join(',')
          })
            .then((res) => {
              this.loading = false;
              if (res.data) {
                let [th, filekey, data, fileName] = [[], [], [], ''];
                
                fileName = res.data.filename;
                filekey = res.data.fileKey;
                th = res.data.header;
                data = data.concat(res.data.export);
                this.$exportExcel(th, filekey, fileName, data);
                
                this.$message.success('批量导出成功');
                this.ids = [];
                this.getList();
              }
            })
            .catch((err) => {
              this.$message.error('导出失败：' + (err.message || '未知错误'));
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message.info('已取消导出');
        });
    },

    // 列表
    getList() {
      this.loading = true;
      leaderListApi(this.tableFrom)
        .then(async (res) => {
          let data = res.data;
          // 为每行数据添加isChecked属性，用于复选框绑定
          this.tableList = data.list.map((item) => {
            return {
              ...item,
              isChecked: this.ids.includes(item.id),
            };
          });
          this.total = res.data.count;
          this.loading = false;

          // 更新全选状态
          this.isAllSelected = this.selectableAgents.length > 0 && this.ids.length === this.selectableAgents.length;
        })
        .catch((res) => {
          this.loading = false;
          this.$message.error(res.msg);
        });
    },
    // 表格搜索
    userSearchs() {
      this.tableFrom.page = 1;
      this.getList();
    },

    // 结算所有代理费用
    settlementAll() {
      this.$confirm('确定要结算所有代理费用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true;
          settlementAllApi()
            .then((res) => {
              this.$message.success(res.msg || '结算成功');
              this.getList();
            })
            .catch((err) => {
              this.$message.error(err.msg || '结算失败');
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message.info('已取消结算');
        });
    },

    edit(id) {
      this.$modalForm(editApi(id)).then(() => this.getList());
    },

    editBrokerage(id) {
      this.$modalForm(editBrokerageApi(id)).then(() => this.getList());
    },
    selectChild(data) {
      console.log('selectChild==', data);
      this.$refs.stock.modals = true;
      this.$refs.stock.userChildBillAttrs(data);
    },
    async exportMXList(row) {
      let [th, filekey, data, fileName] = [[], [], [], ''];
      let excelData = {
        id: row.id,
        // page: 1,
      };
      let lebData = await this.getExcelData(excelData);
      fileName = lebData.filename;

      filekey = lebData.fileKey;
      // }
      th = lebData.header;
      data = data.concat(lebData.export);
      this.$exportExcel(th, filekey, fileName, data);
    },
    exportSettlementData() {
      this.loading = true;
      settlementLeaderBrokerageApi()
        .then((res) => {
          // resolve(res.data);
          this.loading = false;
          if (res.data) {
            // const { lebData } = res.data;
            // // const { header, fileKey, filename, export: exportData } = data;

            // let [th, filekey, data, fileName] = [[], [], [], ''];

            // fileName = lebData.filename;

            // filekey = lebData.fileKey;
            // // }
            // th = lebData.header;
            // data = data.concat(lebData.export);
            // this.$exportExcel(th, filekey, fileName, data);

            // // this.$exportExcel(header, fileKey, filename, exportData);
            // this.$message.success('导出成功');
            // if (res.data) {
            // const { lebData } = res.data;  // 错误的部分
            
            let [th, filekey, data, fileName] = [[], [], [], ''];

            fileName = res.data.filename;

            filekey = res.data.fileKey;
            
            th = res.data.header;
            data = data.concat(res.data.export);
            this.$exportExcel(th, filekey, fileName, data);

            this.$message.success('导出成功');
          // }
          }
        })
        .catch((err) => {
          // this.loading = false;
          this.$message.error('导出失败：' + (err.message || '未知错误'));
        })
        .finally(() => {
          this.loading = false;
        });

      // try {
      //   this.loading = true;
      //   const res = await axios.get('adminapi/export/settlementLeaderBrokerage');
      //   if (res.data) {
      //     const { data } = res.data;
      //     const { header, fileKey, filename, export: exportData } = data;
      //     this.$exportExcel(header, fileKey, filename, exportData);
      //     this.$message.success('导出成功');
      //   }
      // } catch (error) {
      //   this.$message.error('导出失败：' + (error.message || '未知错误'));
      // } finally {
      //   this.loading = false;
      // }
    },

    getExcelData(excelData) {
      return new Promise((resolve, reject) => {
        leaderBrokerageApi(excelData).then((res) => {
          resolve(res.data);
        });
      });
    },
  },
};
</script>

<style lang="stylus" scoped>
.fa {
  color: #0a6aa1;
  display: block;
}

.sheng {
  color: #ff0000;
  display: block;
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.operation-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.selection-alert {
  margin-bottom: 15px;
}

.selection-count {
  color: #409EFF;
  font-style: normal;
  margin: 0 3px;
}

.disabled-action {
  color: #999;
  cursor: not-allowed;
}
</style>
